package org.study.hadoop.md.ch2;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

/**
 * 数值概要2：给定用户的评论列表，按天计算每小时的平均评论长度。
 */
public class AverageDriver extends Configured implements Tool {
	
	public static class AverageReducer extends Reducer<IntWritable, CountAverageTuple, IntWritable, CountAverageTuple> {
		private CountAverageTuple result = new CountAverageTuple();
		
		@Override
		protected void reduce(IntWritable key, Iterable<CountAverageTuple> values,Context context)
				throws IOException, InterruptedException {
			float sum = 0;
			float count = 0;
			for (CountAverageTuple val : values) {
				sum += val.getCount() * val.getAverage();
				count += val.getCount();
			}
			result.setCount(count);
			result.setAverage(sum / count);
			context.write(key, result);
		}
	}
	
	public static class AverageMapper extends Mapper<Object, Text, IntWritable, CountAverageTuple> {
		private IntWritable outHour = new IntWritable();
		private CountAverageTuple outCountAverage = new CountAverageTuple();
		
		private final static SimpleDateFormat FRMT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		@SuppressWarnings("deprecation")
		@Override
		protected void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
			String strDate = parsed.get("CreationDate");
			String text = parsed.get("Text");
			if (strDate == null || text == null) {
				return;
			}
			try {
				Date creationDate = FRMT.parse(strDate);
				outHour.set(creationDate.getHours());
				outCountAverage.setCount(1);
				outCountAverage.setAverage(text.length());
				context.write(outHour, outCountAverage);
			} catch (ParseException e) {
				e.printStackTrace();
				return;
			}
		}
	}
	
	public static class CountAverageTuple implements Writable {
		private float count = 0f;
		private float average = 0f;
		
		public float getCount() {
			return count;
		}
		public void setCount(float count) {
			this.count = count;
		}
		public float getAverage() {
			return average;
		}
		public void setAverage(float average) {
			this.average = average;
		}

		@Override
		public void write(DataOutput out) throws IOException {
			out.writeFloat(count);
			out.writeFloat(average);
		}

		@Override
		public void readFields(DataInput in) throws IOException {
			count = in.readFloat();
			average = in.readFloat();
		}
		
		@Override
		public String toString() {
			return count + "\t" + average;
		}
	}

	@Override
	public int run(String[] args) throws Exception {
		Path outPath = new Path("out");
		Path inPath = new Path("comment.txt");
		FileSystem fs = outPath.getFileSystem(getConf());
		if (fs.exists(outPath)) {
			fs.delete(outPath, true);
		}
		Job job = Job.getInstance(getConf());
		job.setJarByClass(AverageDriver.class);
		job.setMapperClass(AverageMapper.class);
		job.setCombinerClass(AverageReducer.class);
		job.setReducerClass(AverageReducer.class);
		job.setOutputKeyClass(IntWritable.class);
		job.setOutputValueClass(CountAverageTuple.class);
		FileInputFormat.addInputPath(job, inPath);
		FileOutputFormat.setOutputPath(job, outPath);
		return job.waitForCompletion(true) ? 0 : 1;
	}
	
	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new Configuration(), new AverageDriver(), args);
		System.exit(res);
	}
}
